
from ..base import PermissionRuleHandler, register_handler
import re

@register_handler("custom_sql") 
class CustomSqlHandler(PermissionRuleHandler):
    def get_required_config_keys(self):
        return ["sql_template"]

    def validate_config(self, config):
        return "sql_template" in config

    def generate_sql(self, table_alias: str, config: dict, user: dict) -> str:
        template = config["sql_template"]
        # 安全替换：只允许 {user.xxx}
        def replace_user(match):
            key = match.group(1)
            if key in user:
                val = user[key]
                if isinstance(val, str):
                    return f"'{val}'"
                return str(val)
            return "NULL"
        
        sql = re.sub(r"\{user\.([a-zA-Z_][a-zA-Z0-9_]*)\}", replace_user, template)
        return sql